import {ActionContext} from 'vuex';
import ListModule from '@/store/modules/list-module';
import ListState from '@/store/modules/list-state';
import Ajax from '@/lib/ajax';
import Notification from '@/views/other/notification/notification.vue';

interface NotificationState extends ListState<any> {
    unreadCount: number;
}

class NotificationModule extends ListModule<NotificationState, any, any> {
    state = {
        totalCount: 0,
        currentPage: 1,
        pageSize: 10,
        list: [],
        loading: false,
        unreadCount: 0,
    };
    actions = {
        async getUserNotifications(context: ActionContext<NotificationState, any>, payload: any) {
            context.state.loading = true;
            const response = await Ajax.get('/api/services/app/Notification/GetUserNotifications', {params: payload.data});
            context.state.loading = false;
            context.state.totalCount = response.data.result.totalCount;
            context.state.unreadCount = response.data.result.unreadCount;
            context.state.list = response.data.result.items;
        },
        async setAllNotificationsAsRead(context: ActionContext<NotificationState, any>, payload: any) {
            await Ajax.post('/api/services/app/Notification/SetAllNotificationsAsRead');
            context.state.unreadCount = 0;
        },
        async deleteNotification(context: ActionContext<NotificationState, any>, payload: any) {
            await Ajax.delete('/api/services/app/Notification/DeleteNotification?Id=' + payload.data.id);
        },
        async setNotificationAsRead(context: ActionContext<NotificationState, any>, payload: any) {
            await Ajax.post('/api/services/app/Notification/SetNotificationAsRead', payload.data);
        },
        async batchDeleteNotifications(context:ActionContext<NotificationState, any>,payload:any){
            await Ajax.post('/api/services/app/Notification/BatchDeleteNotifications',payload.data);
        }
    };
    mutations = {
        setCurrentPage(state: NotificationState, page: number) {
            state.currentPage = page;
        },
        setPageSize(state: NotificationState, pageSize: number) {
            state.pageSize = pageSize;
        },
        addNotification(state: NotificationState, notification: any) {
            state.unreadCount += 1;
            state.totalCount += 1;
            state.list.push(notification);
        },
        reduceUnread(state: NotificationState, notification: any) {
            state.list.forEach((item) => {
                if (item.state===0 && item.id === notification.id) {
                    item.state = 1;
                    state.unreadCount-=1;
                }
            });


        },
    };
}

const notificationModule = new NotificationModule();
export default notificationModule;
